package com.newtype.meeting.client.mvc.frontend;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.newtype.meeting.client.AppEvents;
import com.newtype.meeting.client.GMeeting;
import com.newtype.meeting.client.model.Account;
import com.newtype.meeting.client.model.Meeting;
import com.newtype.meeting.client.service.MeetingServiceAsync;

public class StartMeetingListController extends Controller {
	private StartMeetingListView startMeetingListView;
	private MeetingServiceAsync meetingService;
	private Account account;

	public StartMeetingListController() {
		registerEventTypes(AppEvents.ViewStartMeetingList);
	}

	@Override
	protected void initialize() {
		super.initialize();
		startMeetingListView = new StartMeetingListView(this);
		meetingService = Registry.get(GMeeting.MEETING_SERVICE);
		account = Registry.get(GMeeting.ACCOUNT);
	}

	@Override
	public void handleEvent(AppEvent event) {
		EventType type = event.getType();
		if (type == AppEvents.ViewStartMeetingList) {
			onViewStartMeeting(event);
		}
	}

	private void onViewStartMeeting(AppEvent event) {
		final AppEvent ae = new AppEvent(event.getType());
		meetingService.getMeetings(account.getAccountID(),
				new AsyncCallback<List<Meeting>>() {
					@Override
					public void onFailure(Throwable caught) {
						Dispatcher.forwardEvent(AppEvents.Error, caught);
					}

					@Override
					public void onSuccess(List<Meeting> result) {
						List<Meeting> startList = new ArrayList<Meeting>();
						List<Meeting> cancelList = new ArrayList<Meeting>();
						for (Meeting meeting : result) {
							if (meeting.getCancelTAG() != null
									&& meeting.getCancelTAG() == 1) {
								cancelList.add(meeting);
							} else {
								startList.add(meeting);
							}
						}
						ae.setData("starts", startList);
						ae.setData("cancels", cancelList);
						forwardToView(startMeetingListView, ae);
					}
				});
	}

}
